
<template>
  <div class="main">
    <PureTableBar title="证券清偿列表" class="list_hei">
      <template #buttons>
        <el-button type="primary" @click="DialogVisible = true">新增证券清偿 </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" adaptive size="small"
          :data="dataList" max-height="600" :columns="columns" :checkList="checkList" :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button type='primary' text @click="checkDetail(row)">
              查看详情
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
  </div>

  <ReDialog :width="1000" :height="500" :models="DialogVisible" @Closes="cancelTransfer()">
    <template #header>
      <h2 style="text-align: center;">证券清偿窗口</h2>
    </template>
    <template #main>
      <el-scrollbar height="420px">
        <div style="padding:0 10px">
          <div style="margin: 20px 0;">
            资产证券化项目：<el-select placeholder="请选择资产证券化项目" v-model="filterSelectId" style="width:30%">
              <el-option v-for="item in filterDataList" :key="item.assetTransferId" :label="item.assetSecuritizationName"
                :value="item.assetTransferId" @click="filterProject(item)" />
            </el-select>
          </div>
          <div style="margin: 20px 0;">
            费用支付和清偿：<el-select placeholder="请选择费用支付和清偿" v-model="selecType" style="width:30%" @change="changeType()">
              <el-option v-for="item in selectList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </div>
          <div class="middle">
            <div v-if="selecType == '偿还本息'">
              “该项目为一次还本付息类型，该项目一共发行证券{{ formData1.count }}份，每份票面金额100元，总份额{{ formData1.
                accountMoney }}元，票面利率{{ formData1.rate }}%，期限为{{ formData1.date }}天，到期还本付息总计：{{ formData1.payMoney }}元。”
            </div>
            <div v-if="selecType == '证券公司的承销费和管理费'">
              <h3 style="display: flex;align-items: center;justify-content: center;">承销服务费和计划管理费支付通知</h3>
              <p> 尊敬的{{ spvName }}：</p>
              <p>
                &nbsp;&nbsp;鉴于贵司与我司签署的资产证券化项目承销与服务协议约定，请贵司按如下金额方式向我司支付承销服务费和计划管理费。
              </p>
              <p>
                &nbsp;&nbsp;1、 计算方式：本次发行募集资金专用账户实际到账金额：{{ formData2.
                  accountMoney }}元， 承销服务费用计提比例：【 1% /
                年】， 加权平均发行期限：{{ formData2.date }}天，总承销费用{{ formData2.totalExpenses
                }}元 （总承销费用=本次发行募集资金专用账户实际到账金额*承销服务费用计提比例*加权平均发行期限）， 计划管理费用计提比例：【3‰
                /年】，计划管理费{{ formData2.managementFee }}元（计划管理费=本次发行募集资金专用账户实际到账金额*计划管理费用计提比例*加权平均发行期限），合计：{{
                  formData2.payMoney }}元
              </p>
              <p>
                &nbsp;&nbsp;2、 支付方式：请{{ spvName }}（SPV/SPT）在{{ formData2.payYear }}年{{ formData2.payMonth }}月{{
                  formData2.payDay }}日前，将上述金额转账至乙方指定账户： 
              </p>
              <p>
                &nbsp;&nbsp;户    名：XX证券有限责任公司 
              </p>
              <p>
                &nbsp;&nbsp;账    号：XXXXXXXXXXXX
              </p>
              <p>
                &nbsp;&nbsp;开户银行：XX银行XX支行
              </p>
              <div style="display:flex;justify-content: end;margin-top:50px">
                XX证券有限责任公司<br>
                {{ formData2.NowYear }}年{{ formData2.NowMonth }}月{{ formData2.NowDay }}日
              </div>
            </div>
            <div v-if="selecType == '评级机构的评级费用'">
              <h3 style="display: flex;align-items: center;justify-content: center;">资产证券化信用评级协议书 </h3>
              <p> 甲方：{{ spvName }}</p>
              <p> 乙方：xx资信评估投资服务有限公司</p>
              <p> 甲、乙双方遵照国家有关法律、法规、监管部门规定，经平等协商一致，订立本协议书。</p>
              <p> 一、 委托目的 甲方拟申请发行xx年度xx市{{ assetSecuritizationName
              }}（以下简称“本期资产证券化”），经甲乙双方友好协商，甲方聘请乙方为甲方本期资产证券化发行事宜提供信用评级服务。 
              </p>
              <p> 二、 委托范围 </p>
              <p> 2.1  甲方委托乙方为甲方本期资产证券化进行首次评级。</p>
              <p> 2.2  本期资产证券化存续期为{{ formData3.date }}天，本期资产证券化发行成功后，在存续期间，乙方须对本期资产证券化提供跟踪评级服务。 </p>
              <p> 三、 委托期限 </p>
              <p> 3.1  甲方委托乙方为本期资产证券化进行首次信用评级及后续跟踪评级的期限从本协议生效之日起至本期资产证券化存续期届满之日止。 </p>
              <p> 3.2  乙方应在本协议生效之日且收到甲方支付的首次评级费用后进行首次评级。 </p>
              <p> 3.3  在本期资产证券化存续期内，甲方或本期资产证券化发生对信用状况产生较大影响的事件，乙方应在得到甲方书面告知及相关资料后进行不定期跟踪评级。  </p>
              <p> 3.4  若因甲方原因、不可抗力等意外情况需延长或提前完成评级工作，甲乙双方需另行协商。  </p>
              <p> 四、收费标准及付款方式</p>
              <p> 5.1  评级费用：人民币{{ formData3.payMoneyStr }}(￥{{ formData3.payMoney }})。  </p>
              <p> 5.2  评级费用的范围：上述评级费用包括了乙方为甲方提供首次评级及跟踪评级服务的服务费用、评级项目组差旅费、食宿费等所有费用。 </p>
              <p>
                5.3  付款期限：本协议书生效后，甲方应于三个工作日内向乙方提供的银行付款账号全额支付首次评级费用。年度跟踪评级费用每年收取一次，甲方应于乙方出具跟踪评级报告前的三个工作日内向乙方提供的银行付款账号全额支付跟踪评级费用。
              </p>
              <p> 5.4  付款账号：</p>
              <p> 户  名：xx资信评估投资服务有限公司 </p>
              <p> 开户行：XXXXXXXX</p>
              <p>账  号：XXXXXXXX </p>
            </div>
            <div v-if="selecType == '审计费用'">
              <h3 style="display: flex;align-items: center;justify-content: center;">审计服务合同范</h3>
              <p> 委托方：{{ spvName }}</p>
              <p> 受托方：安永华明会计师事务所</p>
              <p> 依据《中华人民共和国合同法》、《中华人民共和国注册会计师法》、《中国注册会计师独立审计准则》等规定，经双方协商一致，签订本合同，以资共同遵守。 </p>
              <p> 第一条 委托目的和内容  
              </p>
              <p>甲方委托乙方：对基础资产财务状况进行尽职调查和现金流分析，提供会计和税务咨询，在专项计划成立时进行募集资金验资，并在产品存续期间对专项计划进行专项审计，对清算报告进行审计等。   </p>
              <p> 第二条 会计责任与审计责任   </p>
              <p> 1、甲方承担会计责任（管理当局的责任），即建立健全的内部控制制度，保护资产的安全，并保证其提供的全部资料的真实性、完整性和合法性；</p>
              <p> 2、乙方承担审计责任，即依据《中国注册会计师独立审计准则》的规定，对所出具的审计报告承担责任。</p>
              <p> 第三条 甲方义务</p>
              <p> 第四条 乙方义务</p>
              <p> 1、严格依据有关法律、法规和《中国注册会计师独立审计准则》执行业务；</p>
              <p> 2、应于{{ formData4.payYear }}年{{ formData4.payMonth }}月{{ formData4.payDay }}日前出具审计报告；</p>
              <p> 3、对在业务执行过程中获悉的商业秘密保密。 </p>
              <p> 第五条 审计收费 </p>
              <p> 1、根据北京市物价局最新规定和委托项目的工作量、难易及风险程度确定审计费用。 </p>
              <p>
                2、经协商，双方确定本项目的审计费用及付款时间如下：审计费用：{{ formData4.payMoney }}元；</p>
              <p>3、因业务需要由乙方垫付的费用，如差旅费等，由甲方另行全额支付，不计入上述费用。   </p>
              <p> 第六条 违约责任</p>
              <p> 1、由于甲方变更计划，或未及时提供审计所需全部资料（或工作条件）而造成乙方返工、窝工或修改报告，乙方可合理延期出具审计报告或拒绝出具审计报告，甲方应根据乙方实际消耗的工作量另行支付相应费用； </p>
              <p>2、如因甲方原因导致本项目中途停止，乙方所收费用不再退还甲方；   </p>
              <p>3、除因甲方原因以外，乙方未在合同规定期限内提交审计报告，甲方可以拒绝支付服务费用；</p>
              <p>4、如合同任何一方违反上述条款，都应负责赔偿由此而给对方造成的合理损失。</p>
              <p>第七条 争议的解决方式  </p>
              <p>本合同执行过程中如发生争议，双方应及时友好协商解决。经协商不能达成一致时，合同任何一方可向仲裁机构申请仲裁，或直接向人民法院提起诉讼。</p>
              <p>第八条 附则</p>
              <p>本合同自双方法人代表或其授权代表签字签章之日起生效，一式两份，双方各执一份，具有同等法律效力。</p>
              <div style="display:flex;justify-content: space-between;">
                <div>
                  甲方（签字）：{{ spvName }}
                </div>
                <div>
                  乙方（签字）：安永华明会计师事务所
                </div>
              </div>
              <div style="display:flex;justify-content: space-between;">
                <div>
                  {{ formData4.nowYear }}年 {{ formData4.nowMonth }}月 {{ formData4.nowDay }}日
                </div>
                <div>
                  {{ formData4.nowYear }}年 {{ formData4.nowMonth }}月 {{ formData4.nowDay }}日
                </div>
              </div>
            </div>
            <div v-if="selecType == '法律顾问费用'">
              <h3 style="display: flex;align-items: center;justify-content: center;">资产证券化项目专项法律服务合同</h3>
              <p> 第一条   委托 </p>
              <p> 1.1 经各方协商，甲方同意委托乙方提供本合同约定的资产证券化项目专项法律服务；乙方亦同意接受委托，依照本合同及律师执业准则向甲方提供法律服务。</p>
              <p>
                1.2 甲方同意乙方委派律师作为服务团队负责律师，并指派其他律师共同对甲方提供法律服务。乙方可根据项目进展情况调整团队，并应在调整律师团队前向甲方提供调整后的团队成员履历介绍，且获得甲方书面确认。甲方对服务团队成员的服务水平、业务能力、职业道德等存在异议的，有权要求乙方更换，乙方应在接到甲方要求更换的通知后两个工作日内予以更换。 
              </p>
              <p> 1.3 各方确认，乙方受甲方委托，提供法律服务具体内容如下：</p>
              <p> 1.3.1 协助甲方及参与本项目的其他机构制定本项目资产证券化的总体方案，对相关问题进行论证，为甲方、银行提供相关法律咨询； </p>
              <p> 1.3.2 根据法律法规的要求，为法律意见书出具之目的，对本项目的基础资产以及交易各方进行法律尽职调查并出具法律尽职调查报告； </p>
              <p> 1.3.3 审查本次资产证券化交易各方的主体资格、交易结构，对资产的真实出售和风险隔离及其他合规性进行法律判断，出具专项法律意见；</p>
              <p> 1.3.4 起草或修改与本次交易相关的全部法律文件，包括但不限于信托合同、服务合同、托管合同、主定义表、主承销协议、承销团协议等</p>
              <p> 1.3.5 审查本次资产证券化的发行说明书及其他信息披露文件；</p>
              <p> 1.3.6 协助甲方与银行办理信托财产交付手续，确保其合法性；</p>
              <p> 1.3.7 法律法规规定或监管机构要求或甲方、银行就本项目所要求的其他法律服务</p>
              <p> 第二条   法律服务费用 </p>
              <p> 2.1 基于本合同项下的法律服务，各方同意，甲方应付乙方的法律服务费用总额为￥{{ formData5.payMoney }} 元（大写{{ formData5.payMoneyStr }}）。 </p>
              <p> 2.2乙方律师受甲方委托，从事与甲方业务有关的活动而发生必要及合理的费用，包括但不限于交通、住宿等费用，由甲方按实际发生额实报实销</p>
              <p> 2.3 乙方指定的收款账户：</p>
              <p> 开户名：北京市金杜律师事务所</p>
              <p> 账  号：XXXXXXXX</p>
              <p> 开户行：XXXXXXXX</p>
              <div style="display:flex;justify-content: end;margin-top:50px">
                甲方：{{ spvName }}
              </div>
              <div style="display:flex;justify-content: end;margin-top:50px">
                乙方：北京市金杜律师事务所
              </div>
            </div>
            <div v-if="selecType == '剩余收入分配'">
              该项目为一次还本付息类型，该项目一共发行证券{{ formData6.count }}份，每份票面金额100元，总份额{{ formData6.
                accountMoney }}元，票面利率{{ formData6.rate }}%，期限为{{ formData6.date }}天，到期还本付息总计：{{ formData6.payMoney1
  }}元。该项目资产池产生收入期限内总计{{ accountReceivableAmount }}元，各机构服务费一共{{ formData6.anotherMoney }}元；偿还本息和各机构服务费后剩余资金{{
  formData6.leaveMoney }}元，确认无误后请向XX有限公司（发起人）转入剩余资金。
            </div>
          </div>
          <el-form label-width="180px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="转账方：">
                  {{ payData.fromTransactionsUserId }}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="收款方：">
                  {{ payData.toTransactionsUserId }}
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="转账金额：">
                  {{ payData.amount }}元
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveTransfer()"> 确定 </el-button>
        <el-button @click="cancelTransfer()"> 取消 </el-button>
      </span>
    </template>
  </ReDialog>


  <ReDialog :width="800" :height="400" :models="showComfirmDialog" @Closes="showComfirmDialog = false">
    <template #header>
      <h2 style="text-align: center;">证券清偿窗口</h2>
    </template>
    <template #main>
      <PureTableBar title="证券清偿列表" class="list_hei">
        <template v-slot="{ size, checkList }">
          <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" adaptive size="small"
            :data="dataList1" max-height="600" :columns="columns1" :checkList="checkList" :header-cell-style="{
              background: 'var(--el-table-row-hover-bg-color)',
              color: 'var(--el-text-color-primary)'
            }">
          </pure-table>
        </template>
      </PureTableBar>
    </template>
  </ReDialog>
</template>
<script setup lang='ts'>
import {
  CirclePlusFilled
} from "@element-plus/icons-vue"; import {
  GetSPVName,
  GetPassAuditProjectName,
  GetExcessCollateral,
  FinancialTransactionsUsersGetByUsername,
  TransactionsOredrsCreate,
  GetByAssetTransferId,
  GetSmallLoanCreditbalance,
  GetLegalFinalMaturityDate,
  TransferToInvestor,
  UpdateSpvBalance,
  IsTransferService,
  SecuritiesServiceChargCreate,
  GetLiquidationOfSecuritiesList,
  GetListBySecurityCreditRatingId,
  GetSettlementTime
} from "@/api/stu/SupplyChainFinance";
import { emitter } from "@/utils/mitt";
import { priceUppercase } from "@pureadmin/utils";
import { convertCurrency } from "@/utils/transferNumberToChinese";
import { ElMessage } from "element-plus";
import qs from "qs";
import { ref, reactive, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { PureTableBar } from "@/components/RePureTableBar";
const route = useRoute();
const baseDate = ref()
const showComfirmDialog = ref(false)
const formData1 = reactive({
  count: 0,
  accountMoney: 0,
  payMoney: 0,
  date: 0,
  rate: 0,
})
const formData2 = reactive({
  accountMoney: 0,
  date: '',
  totalExpenses: 0,//总承销费用
  managementFee: 0,//计划管理费
  payMoney: 0,//总费用
  payYear: '',
  payMonth: '',
  payDay: '',
  NowYear: '',
  NowMonth: '',
  NowDay: '',
})

const formData3 = reactive({
  date: '',
  payMoney: 0,
  payMoneyStr: ''
})

const formData4 = reactive({
  payYear: '',
  payMonth: '',
  payDay: '',
  nowYear: '',
  nowMonth: '',
  nowDay: '',
  payMoney: ''
})

const formData5 = reactive({
  payMoney: 0,
  payMoneyStr: ''
})

const formData6 = reactive({
  count: 0,
  accountMoney: 0,
  date: 0,
  rate: 0,
  payMoney1: '',//还本
  anotherMoney: '',
  leaveMoney: '',
})

const payData = reactive({
  fromTransactionsUserId: '',
  toTransactionsUserId: '',
  amount: 0,
})


const dataList1 = ref([])
const columns1: TableColumnList = [
  {
    label: "序号",
    type: "index",
    fixed: "left",
    minWidth: 50
  },
  {
    label: "转账方",
    prop: "fromName",
  },
  {
    label: "收款方",
    prop: "toAccount",
  },
  {
    label: "金额（元）",
    prop: "banlance",
  },
];
const columns: TableColumnList = [
  {
    label: "序号",
    type: "index",
    fixed: "left",
    minWidth: 50
  },
  {
    label: "项目名称",
    prop: "securityCreditRatingName",
  },
  {
    label: "操作",
    prop: "operation",
    width: 300,
    slot: "operation"
  },
];
const dataList = ref([])
const spvName = ref() //spvName
const accountReceivableAmount = ref()
const filterDataList = ref([])
const filterSelectId = ref('') //转移id
const assetPoolId = ref()
const selecType = ref('')
const assetSecuritizationName = ref()
const securityCreditRatingId = ref()
const legalDate = ref()
const selectList = ref([
  {
    name: '偿还本息',
    value: '偿还本息'
  },
  {
    name: '证券公司的承销费和管理费',
    value: '证券公司的承销费和管理费'
  },
  {
    name: '评级机构的评级费用',
    value: '评级机构的评级费用'
  },
  {
    name: '审计费用',
    value: '审计费用'
  }, {
    name: '法律顾问费用',
    value: '法律顾问费用'
  },
  {
    name: '剩余收入分配',
    value: '剩余收入分配'
  }
])
const DialogVisible = ref(false)

async function changeType() {
  if (filterSelectId.value == '') {
    ElMessage.warning('请先选择资产证券化项目')
    selecType.value = ''
  } else {
    //处理不同的type数据
    if (selecType.value == '偿还本息') {
      formData1.accountMoney = Number(baseDate.value.expectedIssueSize)
      formData1.rate = Number(baseDate.value.expectedIssueRate)
      formData1.date = Number(baseDate.value.productTerm)
      formData1.count = Number(baseDate.value.expectedIssueSize / 100)
      formData1.payMoney = Number(baseDate.value.expectedIssueSize) * (Number(baseDate.value.expectedIssueRate) / 360 / 100) * Number(baseDate.value.productTerm) + Number(baseDate.value.expectedIssueSize)
      formData1.payMoney = parseInt(Number(formData1.payMoney))
    }
    if (selecType.value == '证券公司的承销费和管理费') {
      formData2.accountMoney = Number(baseDate.value.expectedIssueSize)
      formData2.date = Number(baseDate.value.productTerm)
      formData2.totalExpenses = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
      formData2.totalExpenses = formData2.totalExpenses.toFixed(2)
      formData2.managementFee = Number(baseDate.value.expectedIssueSize) * (3 / 360 / 1000) * Number(baseDate.value.productTerm)
      formData2.managementFee = formData2.managementFee.toFixed(2)
      formData2.payMoney = Number(formData2.totalExpenses) + Number(formData2.managementFee)
      let resStartData = await GetSettlementTime(qs.stringify({
        assetPoolId: assetPoolId.value
      }))
      if (resStartData.success) {
        const dataArr = resStartData.data.substring(0, 10).split('-')
        formData2.NowYear = dataArr[0]
        formData2.NowMonth = dataArr[1]
        formData2.NowDay = dataArr[2]
        const endDate = addDay(90, resStartData.data.substring(0, 10))
        formData2.payYear = endDate.getFullYear();
        formData2.payMonth = String(endDate.getMonth() + 1).padStart(2, '0');
        formData2.payDay = String(endDate.getDate()).padStart(2, '0');
      } else {
        ElMessage.warning(resStartData.msg)
      }
    }
    if (selecType.value == '评级机构的评级费用') {
      formData3.date = Number(baseDate.value.productTerm)
      formData3.payMoney = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
      formData3.payMoney = formData3.payMoney.toFixed(2)
      formData3.payMoneyStr = priceUppercase(formData3.payMoney)
    }
    if (selecType.value == '审计费用') {
      let resStartData = await GetSettlementTime(qs.stringify({
        assetPoolId: assetPoolId.value
      }))
      if (resStartData.success) {
        const dataArr = resStartData.data.substring(0, 10).split('-')
        formData4.nowYear = dataArr[0]
        formData4.nowMonth = dataArr[1]
        formData4.nowDay = dataArr[2]
        const endDate = addDay(30, resStartData.data.substring(0, 10))
        formData4.payYear = endDate.getFullYear();
        formData4.payMonth = String(endDate.getMonth() + 1).padStart(2, '0');
        formData4.payDay = String(endDate.getDate()).padStart(2, '0');
        formData4.payMoney = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
        formData4.payMoney = formData4.payMoney.toFixed(2)
      } else {
        ElMessage.warning(resStartData.msg)
      }
    }
    if (selecType.value == '法律顾问费用') {
      formData5.payMoney = Number(baseDate.value.expectedIssueSize) * (0.5 / 360 / 100) * Number(baseDate.value.productTerm)
      formData5.payMoney = formData5.payMoney.toFixed(2)
      formData5.payMoneyStr = priceUppercase(formData5.payMoney)
    }
    if (selecType.value == '剩余收入分配') {
      formData6.accountMoney = Number(baseDate.value.expectedIssueSize)
      formData6.date = Number(baseDate.value.productTerm)
      formData6.rate = Number(baseDate.value.expectedIssueRate)
      formData6.count = Number(baseDate.value.expectedIssueSize / 100)
      formData6.payMoney1 = Number(baseDate.value.expectedIssueSize) * (Number(baseDate.value.expectedIssueRate) / 360 / 100) * Number(baseDate.value.productTerm) + Number(baseDate.value.expectedIssueSize) //还本付息
      formData6.payMoney1 = parseInt(formData6.payMoney1)
      // 证券公司的承销费和管理费
      const pay1 = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
      const pay2 = Number(baseDate.value.expectedIssueSize) * (3 / 360 / 1000) * Number(baseDate.value.productTerm)
      // 评级机构的评级费用
      const pay3 = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
      //审计费
      const pay4 = Number(baseDate.value.expectedIssueSize) * (1 / 360 / 100) * Number(baseDate.value.productTerm)
      // 法律顾问费用
      const pay5 = Number(baseDate.value.expectedIssueSize) * (0.5 / 360 / 100) * Number(baseDate.value.productTerm)
      formData6.anotherMoney = pay1 + pay2 + pay3 + pay4 + pay5
      formData6.anotherMoney = formData6.anotherMoney.toFixed(2)
      formData6.leaveMoney = accountReceivableAmount.value - formData6.payMoney1 - formData6.anotherMoney
      formData6.leaveMoney = parseInt(formData6.leaveMoney)
    }
    openPayDialog()
  }
}
async function saveTransfer() {
  if (selecType.value == '偿还本息') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '投资者',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data1 = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = qs.stringify({
        fromTransactionsUserId: toTransactionsUserId,
        money: formData1.payMoney,
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res2 = await TransferToInvestor(data2)
      if (res2.success) {
        ElMessage.success(`成功支付${spvName.value}到期还本付息总计${formData1.payMoney}`)
        emitter.emit('refreshMoney')
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "投资者",
          banlance: formData1.payMoney,
          type: 2
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  }
  if (selecType.value == '证券公司的承销费和管理费') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '证券承销商',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res = await FinancialTransactionsUsersGetByUsername(data)
      const fromTransactionsUserId = res.data.transactionsUserId
      const data1 = qs.stringify({
        userName: '证券承销商',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = {
        fromTransactionsUserId: fromTransactionsUserId,
        toTransactionsUserId: toTransactionsUserId,
        menuId: '',
        amount: formData2.payMoney,
        description: '承销服务费和计划管理费',
        taskId: route.query.taskId,
        planId: route.query.planId,
      }
      let res2 = await TransactionsOredrsCreate(data2)
      if (res2.success) {
        ElMessage.success(res2.msg)
        emitter.emit('refreshMoney')
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "证券承销商",
          banlance: formData2.payMoney,
          type: 2
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  } if (selecType.value == '评级机构的评级费用') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '信用评级机构',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data1 = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = qs.stringify({
        transactionsUserId: toTransactionsUserId,
        balance: formData3.payMoney
      })
      let res2 = await UpdateSpvBalance(data2)
      if (res2.success) {
        ElMessage.success(`成功支付信用评级机构评级费用总计${formData3.payMoney}`)
        emitter.emit('refreshMoney')
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "信用评级机构",
          banlance: formData3.payMoney,
          type: 2
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  } if (selecType.value == '审计费用') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '会计师事务所',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data1 = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = qs.stringify({
        transactionsUserId: toTransactionsUserId,
        balance: formData4.payMoney
      })
      let res2 = await UpdateSpvBalance(data2)
      if (res2.success) {
        ElMessage.success(`成功支付安永华明会计师事务所费用总计${formData4.payMoney}`)
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "会计师事务所",
          banlance: formData4.payMoney,
          type: 2
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        emitter.emit('refreshMoney')
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  } if (selecType.value == '法律顾问费用') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '律师事务所',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data1 = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = qs.stringify({
        transactionsUserId: toTransactionsUserId,
        balance: formData5.payMoney
      })
      let res2 = await UpdateSpvBalance(data2)
      if (res2.success) {
        ElMessage.success(`成功支付北京市金杜律师事务所费用总计${formData5.payMoney}`)
        emitter.emit('refreshMoney')
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "律师事务所",
          banlance: formData5.payMoney,
          type: 2
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  } if (selecType.value == '剩余收入分配') {
    const params = qs.stringify({
      fromName: 'spv',
      toAccount: '金融公司',
      type: 2,
      securityCreditRatingId: securityCreditRatingId.value,
    })
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await IsTransferService(params, data)
    if (!res.data) {
      const data = qs.stringify({
        userName: 'SPV',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res = await FinancialTransactionsUsersGetByUsername(data)
      const fromTransactionsUserId = res.data.transactionsUserId
      const data1 = qs.stringify({
        userName: '金融公司',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res1 = await FinancialTransactionsUsersGetByUsername(data1)
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = {
        fromTransactionsUserId: fromTransactionsUserId,
        toTransactionsUserId: toTransactionsUserId,
        menuId: '',
        amount: formData6.leaveMoney,
        description: '剩余收入分配',
        taskId: route.query.taskId,
        planId: route.query.planId,
      }
      let res2 = await TransactionsOredrsCreate(data2)
      if (res2.success) {
        ElMessage.success(res2.msg)
        const data = {
          securitiesServiceChargeId: "",
          taskId: route.query.taskId,
          planId: route.query.planId,
          securityCreditRatingId: securityCreditRatingId.value,
          fromName: "spv",
          toAccount: "金融公司",
          banlance: formData6.leaveMoney,
          type: 2,
          isAddAnswer: true,
          assetSecuritizationName: assetSecuritizationName.value
        }
        let res4 = await SecuritiesServiceChargCreate(data)
        emitter.emit('refreshMoney')
        cancelTransfer()
      } else {
        ElMessage.error(res2.msg)
      }
    } else {
      ElMessage.warning('此项目已支付款项！')
    }
  }
  getList()
}

function cancelTransfer() {
  selecType.value = ''
  filterSelectId.value = ''
  DialogVisible.value = false
  payData.fromTransactionsUserId = ''
  payData.amount = null
  payData.toTransactionsUserId = ''
}
async function filterProject(item) {
  assetPoolId.value = item.assetPoolId
  assetSecuritizationName.value = item.assetSecuritizationName
  securityCreditRatingId.value = item.securityCreditRatingId
  const data1 = qs.stringify({
    assetTransferId: item.assetTransferId
  })
  //资产池里面的发行规模
  let res = await GetByAssetTransferId(data1)
  if (res.success) {
    baseDate.value = res.data
  } else {
    ElMessage.warning(res.msg)
  }
  let res1 = await GetSPVName(data1)
  if (res1.success) {
    spvName.value = res1.data.spvCompanyName
  } else {
    ElMessage.warning(res1.msg)
  }
  // 资产池本金
  const data2 = qs.stringify({
    assetPoolId: assetPoolId.value
  })
  let res2 = await GetSmallLoanCreditbalance(data2)
  if (res2.success) {
    accountReceivableAmount.value = res2.data
  } else {
    ElMessage.error(res2.msg)
  }
  const data3 = qs.stringify({
    securityCreditRatingId: securityCreditRatingId.value
  })
  let res3 = await GetLegalFinalMaturityDate(data3)
  if (res3.success) {
    legalDate.value = res3.data.substring(0, 10)
  } else {
    ElMessage.error(res3.msg)
  }
}
onMounted(async () => {
  getList()
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  }
  let res = await GetPassAuditProjectName(data)
  if (res.success) {
    filterDataList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
})

async function getList() {
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  }
  let res = await GetLiquidationOfSecuritiesList(data)
  if (res.success) {
    dataList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
}

function addDay(dayNumber, dateStr) {
  var date = dateStr ? new Date(dateStr) : new Date();
  var ms = dayNumber * (1000 * 60 * 60 * 24);
  var newDate = new Date(date.getTime() + ms);
  return newDate;
}
function openPayDialog() {
  if (filterSelectId.value == '') {
    ElMessage.warning('请先选择资产证券化项目')
    return
  }
  if (selecType.value == '') {
    ElMessage.warning('请先选择费用支付和清偿类型')
    return
  }
  if (selecType.value == '偿还本息') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '投资人'
    payData.amount = formData1.payMoney
  }
  if (selecType.value == '证券公司的承销费和管理费') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '证券承销商'
    payData.amount = formData2.payMoney
  } if (selecType.value == '评级机构的评级费用') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '信用评级机构'
    payData.amount = formData3.payMoney
  } if (selecType.value == '审计费用') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '安永华明会计师事务所'
    payData.amount = formData4.payMoney
  } if (selecType.value == '法律顾问费用') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '北京市金杜律师事务所'
    payData.amount = formData5.payMoney
  } if (selecType.value == '剩余收入分配') {
    payData.fromTransactionsUserId = spvName.value
    payData.toTransactionsUserId = '金融公司'
    payData.amount = formData6.leaveMoney
  }
}

async function checkDetail(row) {
  const params = qs.stringify({
    securityCreditRatingId: row.securityCreditRatingId,
    type: 2,
  })
  let res = await GetListBySecurityCreditRatingId(params)
  if (res.success) {
    dataList1.value = res.data
    showComfirmDialog.value = true
  } else {
    ElMessage.error(res.msg)
  }
}
</script>
<style scoped lang="scss">
@import url(@/style/CreditComm.scss);

.contain {
  width: 100%;
  height: 100%;
  padding: 10px;
  overflow: scroll;
}

.middle {
  width: 100%;
  border: 1px solid #ccc;
  overflow: scroll;
  padding: 2%;
  text-align: start;
}

.con-left {
  width: 100%;
}

.con-right {
  flex: 1;
  display: flex;
  background-color: red;
}

:deep(.el-form-item__label) {
  font-weight: 700
}
</style>
